package com.xianniu.ltc.aspect;

import cn.devezhao.persist4j.Entity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rebuild.core.configuration.general.FormsBuilder;
import com.rebuild.core.metadata.MetadataHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author wangruijie
 * 实体新增/修改保存触发切面操作
 *
 */
@Slf4j
@Aspect
@Component
public class PrintAfterAspect {

    //拦截指定的方法:printPreviewH5  新前端点击打印按钮触发
    @Pointcut("execution(public * com.rebuild.web.general.GeneralModelController.printPreviewH5(..))")
    public void excuteService() {}

    @AfterReturning(returning = "ret",pointcut = "excuteService()")
    public void doAfterReturning(Object ret) throws Throwable {
        log.info("打印方法触发修改可重复文本数据解析为明细切面类----->PrintAfterAspect开始");
        JSONObject jsonObject = (JSONObject) ret;
        JSONObject contentBody = jsonObject.getJSONObject("contentBody");
        // 实体名称
        String entity = contentBody.getString("entity");
        final Entity entityMeta = MetadataHelper.getEntity(entity);
        JSONArray elements = contentBody.getJSONArray("elements");
        for (Object o: elements) {
            JSONObject jo = (JSONObject) o;
            // 获取返回值中的可重复文本进行再次赋值处理
            if (jo.getString("field").equalsIgnoreCase("kechongfuwenben")){
                JSONArray elements2 = jo.getJSONArray("value");
                if (elements2 == null){
                    jo.put("value", new JSONArray());
                    log.info("对于可添加明细的字段，获取返回值中的可重复文本为空，不进行处理------->FormModelAfterAspect结束");
                    return;
                }
                FormsBuilder.instance.buildElementsAspect(elements2, entityMeta);
                jo.put("value", elements2);
                log.info("对于可添加明细的字段，获取返回值中的可重复文本进行再次赋值处理------->FormModelAfterAspect结束");
                return;
            }
        }
        log.info("打印方法触发修改可重复文本数据解析为明细切面类----->PrintAfterAspect结束");
    }
}